package org.example.shoppingBrowser.common;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 导出excel工具
 */
@Slf4j
@Component
public class ExportExcelUtils {
    public void export(String fileName, List<?> dataList, HttpServletResponse response){
        if (CollectionUtils.isEmpty(dataList)){
            log.error("导出excel表格为空");
            return;
        }
        // 实体类
        final Class<?> aClass = dataList.get(0).getClass();

        // 设置请求头参数
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 输出文件流
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, fileName), aClass, dataList);
            // 输出文件流
//            FileOutputStream fos = new FileOutputStream("D:/lovo/lovo-project/进销存系统/"+fileName+".xls");
            workbook.write(outputStream);
        } catch (IOException e) {
            log.error("导出excel表格异常: " + e.getMessage(), e);
        }
    }
}
